package chapters22.class1;


import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by xinxuchu on 2020/8/18.
 */
public class simpleFormatter {

    static class Student{

        @Label("姓名")
        String name;

        @Format(pattern = "yyyy-MM-dd")
        Date born;

        double score;

        public Student(String name, Date born, double score) {
            this.name = name;
            this.born = born;
            this.score = score;
        }
    }

    public static String format(Object object) {
        Class<?> cls = object.getClass();
        StringBuilder sb = new StringBuilder();
        try {
            for (Field f : cls.getDeclaredFields()) {//用反射获取类中的字段
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                Label label = f.getAnnotation(Label.class);
                String name = label != null ? label.value() : f.getName();

                Object value = f.get(object);//获取这个字段的的值

                if (value!=null&&f.getType() == Date.class){
                    value = formatDate(f,value);
                }

                sb.append(name +":"+value+"\n");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private static Object formatDate(Field f,Object value){
        Format format = f.getAnnotation(Format.class);
        if (format!=null){
            SimpleDateFormat sdf = new SimpleDateFormat(format.pattern());
            sdf.setTimeZone(TimeZone.getTimeZone(format.Timezone()));
            return sdf.format(value);
        }
        return value;
    }


    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Student zhangsan = new Student("张三",sdf.parse("1995-12-12"),82.36);
        System.out.println(simpleFormatter.format(zhangsan));
    }
}
